<?php

class Schedule extends CI_Controller {

    function __construct() {
        parent::__construct();
        
        //Set folder to load view (under View folder)
        $this->layouts->set_view_folder('schedule');
        
        //Load models
        $this->load->model('schedule_model');
        
        //Load JS and CSS
        $this->layouts->set_js('schedule/date_picker');
        $this->layouts->set_js('schedule/schedule_validation');
        $this->layouts->set_css('date_picker/date_picker');
        
        //Load libraries
        $this->load->helper('form_helper');
    }

    function index() {
        $data['schedule'] = $this->schedule_model->load_schedule($this->session->userdata('user_id'));
        $this->layouts->view('show_schedule_content', $data);
    }
//Dummy login and logout function for testing purpose
    function login() {
        $this->session->set_userdata('user_id', 1);
    }

    function logout() {
        $this->session->unset_userdata('user_id');
        $this->session->sess_destroy();
    }

    function create_schedule() {
        $data['country'] = $this->schedule_model->load_country_list();
        $this->layouts->view('create_schedule_content', $data);
    }

    function do_create_schedule() {
        if ($this->schedule_model->do_create_schedule($this->session->userdata('user_id'))) {
            redirect('schedule');
        }
    }

    function maintain_schedule($schedule_id, $country_id) {
        $data['standard_activity'] = $this->schedule_model->load_standard_activity($country_id);
        $data['schedule_detail'] = $this->schedule_model->load_schedule_detail($schedule_id);
        $data['schedule_id'] = $schedule_id;
        $data['country_id'] = $country_id;
        $this->layouts->view('maintain_schedule_content', $data);
    }

    function delete_schedules() {
        $schedule_id = $this->input->post('schedule_id');
        if ($schedule_id != null) {
            foreach ($schedule_id as $row) {
                $schedule_detail = $this->schedule_model->load_schedule_detail($row);
                if (count($schedule_detail["activities"]) == 0) {
                    $this->schedule_model->delete_schedule($row);
                }
            }
        }
        redirect('schedule');
    }

    function update_schedule($schedule_id) {
        $data['updated_schedule'] = $this->schedule_model->update_schedule($schedule_id);
        $data['country'] = $this->schedule_model->load_country_list();
        $this->layouts->view('edit_schedule_content', $data);
    }

    function do_update_schedule() {
        $this->schedule_model->do_update_schedule();
        redirect('schedule');
    }

    function create_activity() {
        $schedule_id = $this->input->post('schedule_id');
        $country_id = $this->input->post('country_id');
        $sync_gcalendar = $this->input->post('sync_gcalendar');
        $this->schedule_model->create_activity();
        if ($sync_gcalendar == 0) {
            redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
        } else {
            $student_activity_id = $this->db->insert_id();
            if ($this->session->userdata('sessionToken') == false) {
                redirect('schedule/login_google/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id . '/create');
            } else {
                redirect('schedule/add_to_gcalendar/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id);
            }
        }
    }

    function add_to_gcalendar($student_activity_id, $country_id, $schedule_id) {
        //Load relevant client library
        $this->schedule_model->load_calendar_api();
        //Use session token to construct a client, which will be used everytime app access Calendar API
        $client = Zend_Gdata_AuthSub::getHttpClient($this->session->userdata('sessionToken'));
        //Retrieve details of the student activity from database
        $student_activity = $this->schedule_model->load_activity_detail($student_activity_id);
        //Prepare event entry parameters to populate event entry
        $title = $student_activity[0]->activity_title;
        $desc = $student_activity[0]->description;
        $startDate = $student_activity[0]->start_date;
        $startTime = '18:52';
        $endDate = $student_activity[0]->end_date;
        $endTime = '24:00';
        $tzOffset = '+08';
        //Create calendar instance, event instance and populate event attribute
        $gdataCal = new Zend_Gdata_Calendar($client);
        $newEvent = $gdataCal->newEventEntry();

        $newEvent->title = $gdataCal->newTitle($title);
        $newEvent->content = $gdataCal->newContent("$desc");

        $when = $gdataCal->newWhen();
        $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
        $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
        $alert_reminder = $gdataCal->newReminder(null, "alert", null, null, 6);
        $email_reminder = $gdataCal->newReminder(null, "email", null, null, 6);
        $when->reminders = array($alert_reminder, $email_reminder);
        $newEvent->when = array($when);
        //Insert event to calendar server
        $new_event = $gdataCal->insertEvent($newEvent);
        //Retrieve event ID of the inserted event in Googler Calendar Server
        $event_id = $new_event->id->text;
        //Sanitize ID string and save to student_activity table for future retrival
        $fregment = explode(':', $event_id);
        $location = 'https:' . $fregment[1];
        $this->schedule_model->keep_event_id($student_activity_id, $location);
        //Redirect to schedule main page
        redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
    }

    function update_activity($student_activity_id) {
        $data['updated_activity'] = $this->schedule_model->update_activity($student_activity_id);
        $this->layouts->view('edit_activity_content', $data);
    }

    function do_update_activity() {
        $schedule_id = $this->input->post('schedule_id');
        $country_id = $this->input->post('country_id');
        $student_activity_id = $this->input->post('student_activity_id');
        $location = $this->input->post('location');
        $this->schedule_model->do_update_activity();

        if ($location == null) {
            redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
        } else {
            $this->session->set_userdata('location', $location);
            if ($this->session->userdata('sessionToken') == false) {
                redirect('schedule/login_google/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id . '/update');
            } else {
                redirect('schedule/update_gcalendar/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id);
            }
        }
    }

    function update_gcalendar($student_activity_id, $country_id, $schedule_id) {
        //Load relevant client library
        $this->schedule_model->load_calendar_api();
        //Use session token to construct a client, which will be used everytime app access Calendar API
        $client = Zend_Gdata_AuthSub::getHttpClient($this->session->userdata('sessionToken'));
        $gdataCal = new Zend_Gdata_Calendar($client);
        //Retrieve details of the student activity from database
        $student_activity = $this->schedule_model->load_activity_detail($student_activity_id);
        //Prepare event entry parameters to populate event entry
        $title = $student_activity[0]->activity_title;
        $desc = $student_activity[0]->description;
        $eventOld = $gdataCal->getCalendarEventEntry($this->session->userdata('location'));
        $eventOld->title = $gdataCal->newTitle($title);
        $eventOld->content = $gdataCal->newContent("$desc");
        $eventOld->save();
        //Redirect to schedule main page
        redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
    }

    function delete_activity($student_activity_id) {
        $deleted_activity = $this->schedule_model->update_activity($student_activity_id);
        $country_id = $deleted_activity[0]->country_id;
        $schedule_id = $deleted_activity[0]->schedule_id;
        $gcalendar_event_id = $deleted_activity[0]->gcalendar_event_id;
        $this->schedule_model->delete_activity($student_activity_id);
        if ($gcalendar_event_id != null) {
            $this->session->set_userdata('gcalendar_event_id', $gcalendar_event_id);
            if ($this->session->userdata('sessionToken') == false) {
                redirect('schedule/login_google/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id . '/delete');
            } else {
                redirect('schedule/delete_from_gcalendar/' . $country_id . '/' . $schedule_id);
            }
        } else {
            redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
        }
    }

    function delete_from_gcalendar($country_id, $schedule_id) {
        //Load relevant client library
        $this->schedule_model->load_calendar_api();
        //Use session token to construct a client, which will be used everytime app access Calendar API
        $client = Zend_Gdata_AuthSub::getHttpClient($this->session->userdata('sessionToken'));
        $gdataCal = new Zend_Gdata_Calendar($client);
        $eventOld = $gdataCal->getCalendarEventEntry($this->session->userdata('gcalendar_event_id'));
        $eventOld->delete();
        redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
    }

    function take_standard_activity() {
        $schedule_id = $this->input->post('schedule_id');
        $country_id = $this->input->post('country_id');
        $this->schedule_model->take_standard_activity();
        redirect('schedule/maintain_schedule/' . $schedule_id . '/' . $country_id);
    }

    function view_standard_activity() {
        $data['schedule_id'] = $this->input->post('schedule_id');
        $data['country_id'] = $this->input->post('country_id');
        $data['activity_title'] = $this->input->post('activity_title');
        $data['description'] = $this->input->post('description');
        $data['duration'] = $this->input->post('duration');
        $this->layouts->view('view_standard_activity', $data);
    }

    function login_google($student_activity_id, $country_id, $schedule_id, $operation) {
        //Load relevant client library
        $this->schedule_model->load_calendar_api();
        //Prepare parameters to construct a link for user to grant access to Google Calendar ($next stores return URL)
        $next = base_url() . "schedule/authenticate_app/" . $student_activity_id . '/' . $country_id . '/' . $schedule_id . '/' . $operation;
        $scope = 'https://www.google.com/calendar/feeds/';
        $secure = false;
        $session = true;
        $authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
        echo anchor($authSubUrl, 'As you have chosen to auto-sync your activities in this schedule to your Google Calendar<br/><br/>Please login Google to grant us access to it!<br/><br/>Thank You.');
    }

    function authenticate_app($student_activity_id, $country_id, $schedule_id, $operation) {
        //Load relevant client library
        $this->schedule_model->load_calendar_api();
        //Return URL redirect to this function, take token value appended to return URL and construct a session token
        if ($this->session->userdata('sessionToken') == false && isset($_GET['token'])) {
            $this->session->set_userdata('sessionToken', Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']));
        }
        if ($operation == 'create') {
            redirect('schedule/add_to_gcalendar/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id);
        } else if ($operation == 'update') {
            redirect('schedule/update_gcalendar/' . $student_activity_id . '/' . $country_id . '/' . $schedule_id);
        } else if ($operation == 'delete') {
            redirect('schedule/delete_from_gcalendar/' . $country_id . '/' . $schedule_id);
        }
    }

}

?>
